# -*- coding: utf-8 -*-
"""
189云盘分享码数据模型
@api-version: 1.0.0
"""

from datetime import datetime
from . import db
import json
from typing import Dict, Any, Optional

class Share189Data(db.Model):
    """189云盘分享码数据模型"""
    __tablename__ = 'share_189_data'
    
    # 主键和基础信息
    id = db.Column(db.Integer, primary_key=True, comment='主键ID')
    share_code = db.Column(db.String(50), unique=True, nullable=False, comment='分享码，作为唯一标识')
    access_code = db.Column(db.String(20), comment='访问码')
    description = db.Column(db.String(200), comment='描述信息')
    
    # 状态字段
    status = db.Column(db.Integer, nullable=False, default=0, 
                      comment='状态：0-待解析，1-解析中，2-解析完成，3-解析失败，4-已导入')
    import_status = db.Column(db.Integer, nullable=False, default=0, 
                             comment='导入状态：0-待导入，1-导入中，2-导入成功，3-导入失败')
    
    # 时间字段
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, 
                          onupdate=datetime.utcnow, comment='更新时间')
    
    # 189云盘相关字段
    share_id = db.Column(db.String(100), comment='189云盘分享ID')
    file_id = db.Column(db.String(100), comment='根文件ID')
    file_name = db.Column(db.String(255), comment='分享文件名')
    file_size = db.Column(db.BigInteger, comment='文件大小（字节）')
    is_folder = db.Column(db.Boolean, comment='是否为文件夹：0-文件，1-文件夹')
    share_mode = db.Column(db.String(50), comment='分享模式')
    creator_name = db.Column(db.String(100), comment='分享者昵称')
    creator_id = db.Column(db.String(100), comment='分享者ID')
    share_date = db.Column(db.DateTime, comment='分享时间')
    expire_date = db.Column(db.DateTime, comment='失效时间')
    
    # 文件树JSON数据
    file_tree_json = db.Column(db.Text, comment='完整文件树JSON结构')
    
    # 统计信息
    total_files = db.Column(db.Integer, comment='总文件数量')
    total_folders = db.Column(db.Integer, comment='总文件夹数量')
    total_size = db.Column(db.BigInteger, comment='总大小（字节）')
    max_depth = db.Column(db.Integer, comment='最大目录深度')
    
    # 性能统计
    parse_duration = db.Column(db.Integer, comment='解析耗时（秒）')
    import_duration = db.Column(db.Integer, comment='导入耗时（秒）')
    imported_files = db.Column(db.Integer, comment='已导入文件数')
    imported_size = db.Column(db.BigInteger, comment='已导入大小（字节）')
    
    # 错误信息
    error_message = db.Column(db.Text, comment='错误信息')
    
    # 详细时间记录
    parse_start_time = db.Column(db.DateTime, comment='解析开始时间')
    parse_end_time = db.Column(db.DateTime, comment='解析结束时间')
    import_start_time = db.Column(db.DateTime, comment='导入开始时间')
    import_end_time = db.Column(db.DateTime, comment='导入结束时间')
    
    # 所有者ID
    owner_id = db.Column(db.BigInteger, comment='所有者ID')
    
    def __init__(self, share_code: str, access_code: str = None, description: str = None, owner_id: int = None):
        """初始化分享码数据"""
        self.share_code = share_code
        self.access_code = access_code
        self.description = description
        self.owner_id = owner_id
        self.status = 0  # 待解析
        self.import_status = 0  # 待导入
    
    @property
    def status_text(self) -> str:
        """获取状态文本"""
        status_map = {
            0: '待解析',
            1: '解析中',
            2: '解析成功',
            3: '解析失败',
            4: '已导入'
        }
        return status_map.get(self.status, '未知状态')
    
    @property
    def import_status_text(self) -> str:
        """获取导入状态文本"""
        status_map = {
            0: '待导入',
            1: '导入中',
            2: '导入成功',
            3: '导入失败'
        }
        return status_map.get(self.import_status, '未知状态')
    
    def get_file_tree_data(self) -> Optional[Dict[str, Any]]:
        """获取文件树数据"""
        if not self.file_tree_json:
            return None
        try:
            return json.loads(self.file_tree_json)
        except (json.JSONDecodeError, TypeError):
            return None
    
    def set_file_tree_data(self, data: Dict[str, Any]):
        """设置文件树数据"""
        if data:
            self.file_tree_json = json.dumps(data, ensure_ascii=False)
        else:
            self.file_tree_json = None
    
    def update_from_parse_result(self, parse_result: Dict[str, Any]):
        """从解析结果更新数据"""
        if not parse_result.get('success'):
            self.status = 3  # 解析失败
            self.error_message = parse_result.get('message', '解析失败')
            return
        
        # 更新基本信息
        share_info = parse_result.get('shareInfo', {})
        if share_info:
            self.share_id = str(share_info.get('shareId', ''))
            self.file_id = str(share_info.get('fileId', ''))
            self.file_name = share_info.get('shareName', '')
            self.file_size = share_info.get('fileSize', 0)
            self.is_folder = share_info.get('isFolder', True)
            self.share_mode = str(share_info.get('shareMode', ''))
            
            # 创建者信息
            creator = share_info.get('creator', {})
            if creator:
                self.creator_name = creator.get('nickName', '')
                self.creator_id = creator.get('ownerAccount', '')
        
        # 更新统计信息
        statistics = parse_result.get('statistics', {})
        if statistics:
            self.total_files = statistics.get('totalFiles', 0)
            self.total_folders = statistics.get('totalFolders', 0)
            self.total_size = statistics.get('totalSize', 0)
            self.max_depth = statistics.get('maxDepthReached', 0)
        
        # 保存完整的文件树数据
        self.set_file_tree_data(parse_result)
        
        # 更新状态
        self.status = 2  # 解析成功
        self.error_message = None
    
    def start_parsing(self):
        """开始解析"""
        self.status = 1  # 解析中
        self.parse_start_time = datetime.utcnow()
        self.error_message = None
    
    def finish_parsing(self, success: bool = True, error_message: str = None):
        """完成解析"""
        self.parse_end_time = datetime.utcnow()
        if self.parse_start_time:
            duration = (self.parse_end_time - self.parse_start_time).total_seconds()
            self.parse_duration = int(duration)
        
        if success:
            self.status = 2  # 解析成功
        else:
            self.status = 3  # 解析失败
            self.error_message = error_message
    
    def start_importing(self):
        """开始导入"""
        self.import_status = 1  # 导入中
        self.import_start_time = datetime.utcnow()
    
    def finish_importing(self, success: bool = True, imported_files: int = 0, 
                        imported_size: int = 0, error_message: str = None):
        """完成导入"""
        self.import_end_time = datetime.utcnow()
        if self.import_start_time:
            duration = (self.import_end_time - self.import_start_time).total_seconds()
            self.import_duration = int(duration)
        
        if success:
            self.import_status = 2  # 导入成功
            self.status = 4  # 已导入
            self.imported_files = imported_files
            self.imported_size = imported_size
        else:
            self.import_status = 3  # 导入失败
            if error_message:
                self.error_message = error_message
    
    def to_dict(self, include_file_tree: bool = False) -> Dict[str, Any]:
        """转换为字典"""
        result = {
            'id': self.id,
            'shareCode': self.share_code,
            'accessCode': self.access_code,
            'description': self.description,
            'status': self.status,
            'statusText': self.status_text,
            'importStatus': self.import_status,
            'importStatusText': self.import_status_text,
            'shareId': self.share_id,
            'fileId': self.file_id,
            'fileName': self.file_name,
            'fileSize': self.file_size,
            'isFolder': self.is_folder,
            'shareMode': self.share_mode,
            'creatorName': self.creator_name,
            'creatorId': self.creator_id,
            'shareDate': self.share_date.isoformat() if self.share_date else None,
            'expireDate': self.expire_date.isoformat() if self.expire_date else None,
            'totalFiles': self.total_files,
            'totalFolders': self.total_folders,
            'totalSize': self.total_size,
            'maxDepth': self.max_depth,
            'parseDuration': self.parse_duration,
            'importDuration': self.import_duration,
            'importedFiles': self.imported_files,
            'importedSize': self.imported_size,
            'errorMessage': self.error_message,
            'parseStartTime': self.parse_start_time.isoformat() if self.parse_start_time else None,
            'parseEndTime': self.parse_end_time.isoformat() if self.parse_end_time else None,
            'importStartTime': self.import_start_time.isoformat() if self.import_start_time else None,
            'importEndTime': self.import_end_time.isoformat() if self.import_end_time else None,
            'ownerId': self.owner_id,
            'createdAt': self.created_at.isoformat() if self.created_at else None,
            'updatedAt': self.updated_at.isoformat() if self.updated_at else None
        }
        
        if include_file_tree:
            result['fileTreeJson'] = self.get_file_tree_data()
        
        return result
    
    def to_list_dict(self) -> Dict[str, Any]:
        """转换为列表显示用的字典（简化版）"""
        return {
            'id': self.id,
            'shareCode': self.share_code,
            'accessCode': self.access_code,
            'description': self.description,
            'status': self.status,
            'statusText': self.status_text,
            'fileCount': self.total_files or 0,
            'totalSize': self.total_size or 0,
            'parsedAt': self.parse_end_time.isoformat() if self.parse_end_time else None,
            'createdAt': self.created_at.isoformat() if self.created_at else None
        }
    
    def __repr__(self):
        return f'<Share189Data {self.share_code}>'